package com.ccx.coachsite.ui.customview;

import com.ccx.coachsite.downloadmgr.AsyncImageLoaderStatic;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Button;

public class MaskButton extends Button {

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		// TODO Auto-generated method stub
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
	}

	private boolean isPressed = false, isLoading = false;
	private Drawable defaultDrawable;

	public MaskButton(Context context) {
		super(context);
	}

	public MaskButton(Context paramContext, AttributeSet paramAttributeSet) {
		super(paramContext, paramAttributeSet);
	}

	private String url;

	public void setUrl(String url) {
		this.url = url;
		Drawable cache = AsyncImageLoaderStatic.loadDrawable(url,
				new AsyncImageLoaderStatic.ImageCallback() {

					@Override
					public void imageLoaded(Drawable imageDrawable,
							String imageUrl) {
						if (imageDrawable != null) {
							isLoading = false;
							MaskButton.this
									.setBackgroundDrawable(imageDrawable);
						}
					}
				});
		if (cache != null)
			super.setBackgroundDrawable(cache);
		else
			isLoading = true;
	}

	public String getUrl() {
		return url;
	}

	/**
	 * @param defaultDrawable
	 *            the defaultDrawable to set
	 */
	public void setDefaultDrawable(Drawable defaultDrawable) {
		this.defaultDrawable = defaultDrawable;
	}

	/**
	 * @return the defaultDrawable
	 */
	public Drawable getDefaultDrawable() {
		return defaultDrawable;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
		case MotionEvent.ACTION_MOVE:
			isPressed = true;
			invalidate();
			break;
		default:
			isPressed = false;
			invalidate();
			break;
		}
		return super.onTouchEvent(event);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		if (isLoading && defaultDrawable != null) {
			defaultDrawable.setBounds(
					(getWidth() - defaultDrawable.getIntrinsicWidth()) / 2,
					(getHeight() - defaultDrawable.getIntrinsicHeight()) / 2,
					defaultDrawable.getIntrinsicWidth(),
					defaultDrawable.getIntrinsicHeight());
			defaultDrawable.draw(canvas);
		}
		if (isPressed) {
			Paint paint = new Paint();
			paint.setStyle(Style.FILL);
			paint.setARGB(128, 128, 128, 128);
			canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
		}
	}
}
